package cn.wolfcode.p2p.base.service.impl;

import cn.wolfcode.p2p.base.util.Constants;
import cn.wolfcode.p2p.base.domain.VerifyCodeVo;
import cn.wolfcode.p2p.base.excetion.DisplayableExcetion;
import cn.wolfcode.p2p.base.service.IVerifyCodeService;
import cn.wolfcode.p2p.base.util.DateUtil;
import cn.wolfcode.p2p.base.util.UserContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StreamUtils;

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.UUID;

@Service
@Transactional
public class VerifyCodeServiceImolImpl implements IVerifyCodeService {
    @Value("${msg.url}")
    private String msgUrl;
    @Value("${msg.uid}")
    private String Uid;
    @Value("${msg.key}")
    private String Key;
    @Override
    public void sendVerifyCode(String phoneNumver) {
        //从session中取出时间进行判断间隔
        VerifyCodeVo vo = UserContext.getVerifyCode();
        if (vo == null || DateUtil.getTimeBetween(vo.getSenTime(), new Date()) > 90) {
            //生成验证码
            String randomCode = UUID.randomUUID().toString().substring(0, 4);
            //指定短信的发送
            StringBuilder msg = new StringBuilder(50);
            msg.append("这是您的验证码:").append(randomCode).append("有效时间为").append(Constants.VERFYCODE_VAILD_TIME).append("分钟,请尽快输入");
            //模拟短信的发送 TODO
            try {
                //senRealMsg(phoneNumver, randomCode);
                System.out.println(msg);
                //将数据存到session中
                vo = new VerifyCodeVo();
                vo.setPhoneNumber(phoneNumver);
                vo.setRandomCode(randomCode);
                vo.setSenTime(new Date());
                UserContext.setVerifyCode(vo);
            } catch (Exception e) {
                throw new DisplayableExcetion(e.getMessage());
            }
        } else {
            throw new DisplayableExcetion("发送验证码太频繁,清扫后再试");
        }
    }


    //发送短信
    public void senRealMsg(String phoneNumber, String verifycode) throws Exception {
        URL url = new URL(msgUrl);
        //建立连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置请求的方式
        conn.setRequestMethod("GET");
        //需要拼接的参数
        StringBuilder param = new StringBuilder(50);
        //Uid=本站用户名&Key=接口安全秘钥&smsMob=手机号码&smsText=验证码:8888
        param.append("Uid=").append(Uid)
                .append("&Key=").append(Key)
                .append("&smsMob=").append(phoneNumber)
                .append("&smsText=").append(verifycode);
        ///true设置输出内筒,false表示没有参数需要输出
        conn.setDoOutput(true);
        //在对方服务器写出数据
        conn.getOutputStream().write(param.toString().getBytes("UTF-8"));
        //请求连接
        conn.connect();
        String respStr = StreamUtils.copyToString(conn.getInputStream(), Charset.forName("UTF-8"));
        int respCode = Integer.parseInt(respStr);
        if (respCode < 0) {
            System.out.println("错误码:" + respCode);
            throw new DisplayableExcetion("短信发送异常,请联系管理员");
        }
    }


    @Override
    public boolean validate(String username, String verifycode) {
        //取出对象,对对象中的数据信息进行比对
        VerifyCodeVo vo = UserContext.getVerifyCode();
        System.out.println(vo);
        if (vo != null && //之前发送的验证码
                //vo.getPhoneNumber().equals(username)&&//判断提交的手机号码跟接收短信的手的号码是否一致
                vo.getRandomCode().equalsIgnoreCase(verifycode) &&//忽略大小写,谭政吗有效
                DateUtil.getTimeBetween(vo.getSenTime(), new Date()) <= Constants.VERFYCODE_VAILD_TIME * 60
                ) {
            return true;
        }
        return false;
    }
}
